package net.b521.petshop.service.impl;


import net.b521.petshop.dao.AdminUserMapper;
import net.b521.petshop.dao.model.AdminUser;
import net.b521.petshop.dao.model.AdminUserExample;
import net.b521.petshop.service.AdminUserService;
import net.b521.petshop.service.exception.LoginException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class AdminUserServiceImpl implements AdminUserService {


    @Autowired
    private AdminUserMapper adminUserMapper;

    @Override
    public AdminUser findById(int id) {
        return adminUserMapper.selectByPrimaryKey(id);
        // return adminUserDao.getOne(id);
    }


    @Override
    public List<AdminUser> findAll() {
        AdminUserExample adminUserExample = new AdminUserExample();
        return adminUserMapper.selectByExample(adminUserExample);
    }

    @Override
    public void update(AdminUser adminUser) {
        adminUserMapper.updateByPrimaryKey(adminUser);
        // adminUserDao.save(adminUser);
    }

    @Override
    public int create(AdminUser adminUser) {
        adminUserMapper.insert(adminUser);
        return adminUser.getId();
        // AdminUser adminUser1 = adminUserDao.save(adminUser);
        // return adminUser.getId();
    }

    @Override
    public void delById(int id) {
        // adminUserDao.delete(id);
        adminUserMapper.deleteByPrimaryKey(id);
    }

    @Override
    public AdminUser checkLogin(HttpServletRequest request, String username, String pwd) {
        AdminUserExample adminUserExample = new AdminUserExample();
        adminUserExample.createCriteria().andUsernameEqualTo(username.trim()).andPasswordEqualTo(pwd.trim());
        List<AdminUser> adminUsers = adminUserMapper.selectByExample(adminUserExample);
        AdminUser adminUser = adminUsers.get(0);
        // AdminUser adminUser = adminUserDao.findByUsernameAndPassword(username, pwd);
        if (adminUser != null) {
            request.getSession().setAttribute("login_user", adminUser);
        } else {
            request.getSession().setAttribute("msg","用户名或密码错误");
            throw new LoginException("用户名或密码错误");
        }
        return adminUser;
    }
}
